package com.qingcheng.consumer;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.qingcheng.pojo.goods.Goods;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.pojo.goods.Spu;
import com.qingcheng.service.goods.SkuService;
import com.qingcheng.service.goods.SpuService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SkuConsumer implements MessageListener {

    @Value("${pagePath}")
    private String pagePath;

    @Reference
    private SpuService spuService;

    @Autowired
    private TemplateEngine templateEngine;
    @Reference
    private SkuService skuService;
    @Override
    public void onMessage(Message message) {
        String jsonString = new String(message.getBody());
        System.out.println(jsonString);
        List<String> skuIds = JSON.parseArray(jsonString,String.class);
        List<Sku> skuList = new ArrayList<>();
        for (String skuId : skuIds) {
            Sku sku = skuService.findById(skuId);
            skuList.add(sku);
        }
        //创建页面（每个SKU为一个页面）
        for (Sku sku : skuList) {
            //查询商品信息
            Goods goods = spuService.findGoodsById(sku.getId());
            //获取SPU 信息
            Spu spu = goods.getSpu();
            // 1.上下文
            Context context = new Context();
            //创建数据模型
            Map<String, Object> dataModel = new HashMap();
            dataModel.put("spu", spu);
            dataModel.put("sku", sku);
            context.setVariables(dataModel);
            // 2.准备文件
            File dir = new File(pagePath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File dest = new File(dir, sku.getId() + ".html");// 3.生成页面
            try {
                PrintWriter writer = new PrintWriter(dest, "UTF‐8");
                templateEngine.process("item", context, writer);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

}
